import 'dart:ui';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../core/index.dart';
import '../../core/widgets/toast_notifications.dart';

/// 视频通话界面
class VamosVideoCallInterface extends StatefulWidget {
  final String conversationId;

  const VamosVideoCallInterface({super.key, required this.conversationId});

  @override
  State<VamosVideoCallInterface> createState() =>
      _VamosVideoCallInterfaceState();
}

class _VamosVideoCallInterfaceState extends State<VamosVideoCallInterface>
    with TickerProviderStateMixin {
  late AnimationController _rippleController;
  late AnimationController _pulseController;
  bool _isMicrophoneOn = true;
  bool _isVoiceOn = true;
  bool _isCallEnded = false;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _startCallTimer();
  }

  /// 初始化动画控制器
  void _initializeAnimations() {
    _rippleController = AnimationController(
      duration: const Duration(milliseconds: 3000),
      vsync: this,
    )..repeat();

    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    )..repeat(reverse: true);
  }

  /// 开始通话计时器
  void _startCallTimer() {
    Future.delayed(const Duration(seconds: 12), () {
      if (mounted && !_isCallEnded) {
        _handleCallTimeout();
      }
    });
  }

  /// 处理通话超时
  void _handleCallTimeout() {
    _endCall('The other party did not respond.');
    _sendCallFailedMessage();
  }

  /// 结束通话
  void _endCall(String reason) {
    if (_isCallEnded) return;

    setState(() {
      _isCallEnded = true;
    });

    Navigator.of(context).pop();

    ToastNotificationHelper.showInfoToast(context, message: reason);
  }

  /// 发送通话失败消息
  void _sendCallFailedMessage() {
    final currentUser = userManager.getCurrentUser();
    if (currentUser == null) return;

    chatManager.sendCallFailedMessage(
      conversationId: widget.conversationId,
      senderId: currentUser.uniqueId,
      receiverId: _getParticipantId(),
    );
  }

  /// 获取对方用户ID
  String _getParticipantId() {
    final conversation = chatManager.getConversationById(widget.conversationId);
    return conversation?.participantId ?? '';
  }

  @override
  void dispose() {
    _rippleController.dispose();
    _pulseController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final conversation = chatManager.getConversationById(widget.conversationId);

    if (conversation == null) {
      return Scaffold(body: Center(child: Text('Conversation not found')));
    }

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: _buildVideoCallContent(conversation),
      ),
    );
  }

  Widget _buildVideoCallContent(ChatConversationEntity conversation) {
    return Stack(
      children: [
        // 背景模糊头像
        _buildBlurredBackground(conversation),

        // 主要内容
        Column(
          children: [
            // 顶部关闭按钮
            _buildTopBar(),

            // 中间头像区域
            Expanded(child: _buildAvatarSection(conversation)),

            // 底部操作按钮
            _buildBottomControls(),
          ],
        ),
      ],
    );
  }

  Widget _buildBlurredBackground(ChatConversationEntity conversation) {
    return Positioned.fill(
      child: ImageFiltered(
        imageFilter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Image.asset(
          conversation.participantAvatar,
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 16.h,
        right: 16.w,
        bottom: 16.h,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.close,
              color: Colors.white,
              size: 24.w,
            ).center().inkWell(onTap: () => _endCall('You rejected the call.')),
          ),
        ],
      ),
    );
  }

  Widget _buildAvatarSection(ChatConversationEntity conversation) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 头像和波纹效果
          _buildAvatarWithRipple(conversation),

          // 状态文本
          Text(
            'Waiting to accept invitation...',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily:
                  GoogleFonts.notoSansSc(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
              fontWeight: FontWeight.w400,
            ),
          ).paddingTop(24.h),
        ],
      ),
    );
  }

  Widget _buildAvatarWithRipple(ChatConversationEntity conversation) {
    return AnimatedBuilder(
      animation: _rippleController,
      builder: (context, child) {
        return Stack(
          alignment: Alignment.center,
          children: [
            // 波纹效果
            ...List.generate(4, (index) {
              final delay = index * 0.2;
              final end = delay + 0.6;
              final animation = Tween<double>(begin: 0.0, end: 1.0).animate(
                CurvedAnimation(
                  parent: _rippleController,
                  curve: Interval(
                    delay,
                    end.clamp(0.0, 1.0),
                    curve: Curves.easeOutCubic,
                  ),
                ),
              );

              // 计算透明度和缩放
              final opacity = (1.0 - animation.value) * (0.4 - (index * 0.08));
              final scale = 1.0 + (animation.value * (0.6 + (index * 0.2)));

              return Transform.scale(
                scale: scale,
                child: Opacity(
                  opacity: opacity.clamp(0.0, 1.0),
                  child: Container(
                    width: 120.w,
                    height: 120.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 1.5.w),
                    ),
                  ),
                ),
              );
            }),

            // 头像
            Container(
              width: 120.w,
              height: 120.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white.withOpacity(0.3),
                  width: 2.w,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10.r,
                    spreadRadius: 2.r,
                  ),
                ],
              ),
              child: ClipOval(
                child: Image.asset(
                  conversation.participantAvatar,
                  width: 120.w,
                  height: 120.w,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildBottomControls() {
    return Container(
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).padding.bottom + 32.h,
        left: 32.w,
        right: 32.w,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 麦克风按钮
          _buildControlButton(
            icon: _isMicrophoneOn ? 'microphone_on.png' : 'microphone_off.png',
            onTap: () {
              setState(() {
                _isMicrophoneOn = !_isMicrophoneOn;
              });
            },
          ),

          SizedBox(width: 10.w),

          // 挂断按钮
          _buildControlButton(
            icon: 'hand_off.png',
            onTap: () => _endCall('You rejected the call.'),
          ),

          SizedBox(width: 10.w),

          // 语音按钮
          _buildControlButton(
            icon: _isVoiceOn ? 'voice_on.png' : 'voice_off.png',
            onTap: () {
              setState(() {
                _isVoiceOn = !_isVoiceOn;
              });
            },
          ),
        ],
      ),
    );
  }

  Widget _buildControlButton({
    required String icon,
    required VoidCallback onTap,
  }) {
    return SizedBox(
      width: 64.w,
      height: 64.w,
      child: Image.asset(
        'assets/images/$icon',
        width: 64.w,
        height: 64.w,
      ).center().inkWell(onTap: onTap),
    );
  }
}
